$(function () {
    findById();
})

/**
 * 查询id
 */
function findById() {
    let id = sessionStorage.getItem("userId");
    let result = myAjax("/admin/user/findById", {id: id},"post");
    console.log(result);
    if (result != null) {
        setData(result.model);
    }

}

//赋值
function setData(data) {
    $("#userName").val(data.userName);
    $("#phone").val(data.phone);
    $("#email").val(data.email);
    $("#age").val(data.age);
    $("input[name='sex'][value=" + data.sex + "]").attr("checked", true);
    $("#birthday").val(data.birthday);
    setHobby(data.hobby);
}

function setHobby(data) {
    //将从数据库拿到的数据中的[]和空格置换为空
    let hobby = data.replace("[", "").replace("]", "").replace(" ", "").replace("，",",");
    //将字符串转换为数组
    let hobbys = hobby.split(",");
    //遍历数组
    $('input:checkbox[name="hobby"]').each(function () {
        for(let i = 0; i < hobbys.length; i++) {
            if ($(this).val() == hobbys[i]) {
                //当数据库中的数据与前端页面的复选框value相等时即为选中
                $("input:checkbox[value=" + hobbys[i] +"]").attr('checked', true);
            }
        }
    });
}

//返回用户查询结果页面
function goBack() {
    $('.right').load('/html/admin/user/userManage.html');
}


function userNameRule() {
    let userName = $("#userName").val();
    //定义用户名输入的匹配规则（以字母开头下划线数子结尾的5-15位字符）
    let rule = /^[a-zA-Z]\w{5,15}$/;
    return judge(rule, userName, "userTips", "您输入的格式错误", "");
}

function phoneRule() {
    let phone = $("#phone").val();
    let rule = /^1[3578]\d{9}$/;
    // if(!rule.test(phone)){
    //     $("#phoneTips").html("您输入的格式错误") ;
    //     return false;
    // }else{
    //     $("#phoneTips").html("")
    //     return true;
    // }
    return judge(rule, phone, "phoneTips", "您输入的格式错误", "");
}

function emailRule() {
    let email = $("#email").val();
    let rule = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    // if(!rule.test(email)){
    //     $("#emailTips").html("您输入的格式错误") ;
    //     return false;
    // }else{
    //     $("#emailTips").html("")
    //     return true;
    // }
    return judge(rule, email, "emailTips", "您输入的格式错误", "");
}


function judge(rule, value, tips, errorTips, successTips) {
    if (!rule.test(value)) {
        $("#" + tips).html(errorTips);
        return false;
    } else {
        $("#" + tips).html(successTips);
        return true;
    }
}
//提交表单时再一次判断提交数据是否正确
function save() {
    if (userNameRule() && phoneRule() && emailRule()) {
        let data = {
            id:sessionStorage.getItem("userId"),
            userName: $("#userName").val(),
            phone: $("#phone").val(),
            email: $("#email").val(),
            sex: $('input:radio[name="sex"]:checked').val(),
            age: $("#age").val(),
            birthday: $("#birthday").val(),
            hobby: getHobby().toLocaleString(),
        };
        console.log(data);
        //连接后台servlet
        let result = myAjax("/admin/user/edit", data,"post");
        console.log(result);
        if (result.result == "success") {
            alert("修改成功(=^ ^=)！");
            $('.right').load('/html/admin/user/userManage.html');
        }else if(result.result == "isHave") {
                alert("当前用户名火爆，请另取一个哟亲(=^ ^=)！")
        } else {
            alert("修改失败，请重新输入！");
        }
    }
}

function getHobby() {
    let hobby =[];
    $("input:checkbox[name=hobby]").each(function() {
        if($(this).prop('checked')){
            hobby.push($(this).val());
        }
    })
    return hobby;
}